﻿using java.io;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using yzrilyzr.asn1;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;

namespace FAQ_UI
{
	/// <summary>
	/// PubkeyList.xaml 的交互逻辑
	/// </summary>
	public partial class PubkeyList : Page, MsgPackReceiver
	{
		private List<FAQID> list = new List<FAQID>();

		public PubkeyList()
		{
			InitializeComponent();
			this.DataContext = this;
			update();
		}

		private void update()
		{
			FAQID[] ks = FAQUtil.client.getPubKeys();
			list.Clear();
			list.AddRange(ks);
			mList.notifyDataChanged();
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			FAQUtil.client.addReceiver(this);
			FAQUtil.eventBus.addReceiver(this);
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.client.removeReceiver(this);
			//FAQUtil.eventBus.removeReceiver(this);
		}

		private void AddPubkey(object sender, RoutedEventArgs e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_PUBKEY_SET));
		}

		public List<FAQID> BPubkeyDataSource
		{ get { return list; } }

		public Holder BPubkeyHolder
		{ get { return new Holder(); } }

		public void onItemClick(object listview, OnItemClickEvent e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_PUBKEY_SET).setTo(list[e.index]));
		}

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			if (mp.getCmd() == ToolBar.TOOLBAR_SELECTOR)
			{
				Dispatcher.Invoke(new Action(() =>
				{
					update();
				}));
			}
		}

		public class Holder : FriendHolder
		{
			public override ViewHolder newInstance()
			{
				return new Holder();
			}

			public override void set(int i, object fAQID, IList datalist)
			{
				FAQID faqid = (FAQID)fAQID;
				Name.Text = FAQUtil.getCommNameOrName(faqid);
				Avatar.Drawable = FAQUtil.getAvatar(faqid);
				try
				{
					byte[] pk = FAQUtil.client.getPubKey(faqid);
					string str = ASN1.read(new ByteArrayInputStream(pk)).toString();
					Regex regex = new Regex("name=\".*?\"", RegexOptions.Multiline);
					Match match = regex.Match(str);
					string names = "";
					while (match.Success)
					{
						names += match.Value.Substring(6);
						names = names.Substring(0, names.Length - 1);
						names += " ";
						match = match.NextMatch();
					}
					Description.Text = names;
				}
				catch (Exception ex) { Description.Text = "读取失败"; }
			}
		}
	}
}